package fr.cdesire.sudoku.applet.applet;

import java.applet.Applet;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;

import fr.cdesire.sudoku.applet.utils.Message;

public class MessageAnimeApplet extends Applet implements Runnable {
	
	/**
	 * UID
	 */
	private static final long serialVersionUID = -8154441223893595997L;
	
	private Thread processus = null;
	private int x_coord = 0;
	private int y_coord = 0;
	private int len = 0;
	private int delay = 100;
	private Image img = null;
	private Graphics gi = null;
	private String message;
	
	@Override
	public void init() {
		
		String str = getParameter("speed");
		int fps = (str != null) ? Integer.parseInt(str) : 10;
		delay = (fps > 0) ? (100 / fps) : 10;
		
		message = "";
		setFont(new Font("Arial,Helvetica,sans-serif", Font.PLAIN, 18));
		setBackground(Color.GRAY);
		setForeground(Color.WHITE);
	}
	
	@Override
	public void update(Graphics g) {
		paint(g);
	}
	
	@Override
	public void paint(Graphics g) {

		if (img != null) {
			g.drawImage(img, 0, 3, this);
		}
	}
	
	@Override
	public void run() {
		
		processus.setPriority(Thread.MIN_PRIORITY);
		long startTime = System.currentTimeMillis();
		
		while (processus != null) {
			faireImage();
			repaint();
			x_coord--;
			len = gi.getFontMetrics().stringWidth(message);
			if (x_coord <= -len) {
				x_coord = getSize().width;
			}
			try {
				startTime +=delay;
				Thread.sleep(Math.max(0, startTime-System.currentTimeMillis()));
			} catch (InterruptedException e) {
			}
		}
		processus = null;
	}
	
	@Override
	public void start() {
		if (processus == null) {
			processus = new Thread(this);
			processus.start();
		}
	}

	@Override
	public void stop() {
		if (processus != null) {
			processus.interrupt();
		}
		processus = null;
	}

	private void faireImage() {
		if (len == 0) {
			img = createImage(getSize().width, getSize().height);
			gi = img.getGraphics();
			FontMetrics fm = gi.getFontMetrics();
			x_coord = getSize().width / 2;
			y_coord = (getSize().height - fm.getHeight()) / 2 + fm.getAscent();
		}
		gi.setColor(getBackground());
		gi.fillRect(0, 0, getSize().width, getSize().height);
		gi.setColor(getForeground());
		gi.drawString(message, x_coord, y_coord);
	}
	
	protected void updateMessageAnime(Message message) {
		
		this.message = message.toString();
		this.x_coord = getSize().width / 2;
		switch (message.getNiveau()) {
			case INFO:
				setForeground(Color.WHITE);
				break;
			case WARN:
				setForeground(Color.ORANGE);
				break;
			case ERROR:
				setForeground(Color.RED);
				break;
			default:
				setForeground(Color.WHITE);
		}
		repaint();
	}
}
